# coding=utf-8
import json
import logging
from future.utils import raise_with_traceback
from copy import deepcopy

from common import orm
from common.campaign.db import daily_recharge as DailyRechargeCampaignDb
from common.campaign.model.daily_recharge import DailyRecharge, CAMPAIGN_STATUS, CAMPAIGN_NAME, CAMPAIGN_CONFIG
from common.utils.tz import today_str, now_ts
from common.account.db.account import add_campaign_award_in_transaction
from common.cache import redis_cache
from common.account.db.account import get_protected_user_name
from common.preset.db.banner import get_banner

_LOGGER = logging.getLogger('bigbang')


def add_new_recharge(user_id, price):
    try:
        ongoing_campaign = get_ongoing_campaign()
        if not ongoing_campaign:
            return
        if price >= ongoing_campaign['condition_price']:
            DailyRechargeCampaignDb.create_campaign(user_id, ongoing_campaign['reward_price'], ongoing_campaign)
    except Exception as e:
        _LOGGER.warn('add daily recharge campaign exception: %s', e)


def award(user_id):
    try:
        campaign = DailyRecharge.query.with_for_update().filter(
            DailyRecharge.user_id == user_id).filter(
            DailyRecharge.date == today_str()).filter(
            DailyRecharge.status == CAMPAIGN_STATUS.WAIT).one()
        campaign.status = CAMPAIGN_STATUS.DONE
        campaign.save(auto_commit=False)

        extend = {
            'title': u'充值活动奖励',
            'campaign_id': campaign.id
        }
        add_campaign_award_in_transaction(user_id, campaign.price, extend)
        orm.session.commit()
    except Exception as e:
        orm.session.rollback()
        orm.session.close()
        raise_with_traceback(e)

    user_name = get_protected_user_name(user_id)
    ts = now_ts()
    scrolling_dict = {
        'text': u'恭喜<font color="#ff0000">【%s】</font>获得%s元彩金奖励' % (user_name, campaign.price),
        'params': {
            'ts': ts
        }
    }
    redis_cache.submit_scrolling(json.dumps(scrolling_dict, ensure_ascii=False), ts, key=CAMPAIGN_NAME)
    if redis_cache.get_scrolling_count(CAMPAIGN_NAME) > 20:
        redis_cache.trim_scrolling(CAMPAIGN_NAME)


def get_campaign_status(user_id):
    status = DailyRechargeCampaignDb.get_status(user_id)
    return status.status if status else 0


_BANNER_ID = 8


def get_ongoing_campaign():
    now = now_ts()
    banner = get_banner(_BANNER_ID)
    if banner.start_ts < now < banner.end_ts:
        campaign = deepcopy(CAMPAIGN_CONFIG)
        campaign['start_time'] = banner.start_ts
        campaign['end_time'] = banner.end_ts
        return campaign
    return None
